package com.google.code.lucene.study.chapter1;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

public class Indexer {

	public int index(File indexDir, File dataDir) throws Exception {
		if (!dataDir.exists() || !dataDir.isDirectory()) {
			throw new IOException(dataDir + ":은(는) 존재하지 않거나 디렉토리가 아닙니다.");
		}

		IndexWriter writer = new IndexWriter(indexDir, new StandardAnalyzer(),
				true, IndexWriter.MaxFieldLength.UNLIMITED);
		writer.setUseCompoundFile(false);
		indexDirectory(writer, dataDir);
		int numIndexed = writer.maxDoc();
		writer.optimize();
		writer.close();
		return numIndexed;
	}

	public void indexDirectory(IndexWriter writer, File dir) throws IOException {
		File[] files = dir.listFiles();

		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isDirectory()) {
				indexDirectory(writer, f);
			} else if (f.getName().endsWith(".txt")) {
				indexFile(writer, f);
			}
		}
	}

	public void indexFile(IndexWriter writer, File f) throws IOException {
		if (f.isHidden() || !f.exists() || !f.canRead())
			return;
		System.out.println("Indexing " + f.getCanonicalPath());
		Document doc = new Document();
		doc.add(new Field("contents", new FileReader(f)));
		doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES,
				Field.Index.NOT_ANALYZED));
		writer.addDocument(doc);
	}
}
